<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <el-row>
        <!-- 添加按钮 -->
        <el-col>
          <el-button
            type="primary"
            @click="addRoles"
          >添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 添加角色对话框 -->
      <el-dialog
        title="添加角色"
        :visible.sync="addDialogVisible"
        width="40%"
        :before-close="handleClose"
        @close="rolesClosed"
      >
        <!-- 表单主区域 -->
        <el-form
          :model="rolesRuleForm"
          :rules="rolesFormRules"
          ref="rolesFormRef"
          label-width="80px"
        >
          <!-- 用户名 -->
          <el-form-item
            label="角色名称"
            prop="roleName"
          >
            <el-input v-model="rolesRuleForm.roleName"></el-input>
          </el-form-item>
          <!-- 密码 -->
          <el-form-item
            label="角色描述"
            prop="roleDesc"
          >
            <el-input v-model="rolesRuleForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="addRole"
          >确 定</el-button>
        </span>
      </el-dialog>

      <!-- 角色列表 -->
      <el-table
        :data="rolesList"
        style="width: 100%"
        stripe
        border
      >
        <!-- 展开列 使用模板作用域拿到数据-->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 渲染权限管理列表 -->
            <el-row
              :class="['bdBottom', i1 === 0 ? 'bdTop' : ' ']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级管理的列表 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightById(scope.row, item1.id)"
                >{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级与三级的管理列表 -->
              <el-col :span="19">
                <el-row
                  :class="i2 === 0 ? ' ' : 'bdTop'"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 渲染二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      type="success"
                    >
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 列表列 -->
        <el-table-column
          type="index"
          label="#"
        ></el-table-column>
        <el-table-column
          label="角色名称"
          prop="roleName"
        ></el-table-column>
        <el-table-column
          label="角色描述"
          prop="roleDesc"
        ></el-table-column>
        <el-table-column
          label="操作"
          width="300px"
        >
          <!-- 修改 -->
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editRole(scope.row.id)"
            >编辑</el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteRole(scope.row.id)"
            >删除</el-button>
            <!-- 分配角色 -->
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="setDialogRights(scope.row)"
            >分配角色</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 修改角色信息 -->
      <el-dialog
        title="修改信息"
        :visible.sync="editRoleDialogVisible"
        width="40%"
        :before-close="handleClose"
      >
        <!-- 表单主区域 -->
        <el-form
          :model="editRolesRuleForm"
          :rules="rolesFormRules"
          ref="editRolesFormRef"
          label-width="80px"
        >
          <!-- 用户名 -->
          <el-form-item
            label="角色名称"
            prop="roleName"
          >
            <el-input v-model="editRolesRuleForm.roleName"></el-input>
          </el-form-item>
          <!-- 密码 -->
          <el-form-item
            label="角色描述"
            prop="roleDesc"
          >
            <el-input v-model="editRolesRuleForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer">
          <el-button @click="editRoleDialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="aditRoleInfo"
          >确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分配权限对话框 -->
      <el-dialog
        title="分配权限"
        :visible.sync="setRightDialogVisible"
        width="30%"
        :before-close="handleClose"
        @close="resetDefKeysArr"
      >
        <!-- 主体区域 -->
        <el-tree
          :data="rightsList"
          :props="treeProps"
          show-checkbox
          node-key='id'
          default-expand-all
          :default-checked-keys='defKeysArr'
          ref="treeRef"
        ></el-tree>
        <span slot="footer">
          <el-button @click="setRightDialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="setRightsRolesById"
          >确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  // 注册自动刷新
  inject: ['reload'],
  data() {
    return {
      rolesList: [],
      //添加角色弹出对话框
      addDialogVisible: false,
      //修改角色弹出对话框
      editRoleDialogVisible: false,
      // 分配权限弹出对话框
      setRightDialogVisible: false,
      // 分配权限的列表数据
      rightsList:'',
      //分配权限角色id
      RolesId:'',
      // 分配权限的属性对象
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认选中当前角色下的权限列表id
      defKeysArr:[],
      // 角色添加
      rolesRuleForm: {
        roleName: '',
        roleDesc: ''
      },
      //修改数据
      editRolesRuleForm: '',
      // 验证规则
      rolesFormRules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      // 请求角色列表数据
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      }
      this.rolesList = res.data
    },
    //关闭添加角色对话框
    handleClose(done) {
      done()
    },
    //添加角色打开对话款
    addRoles() {
      this.addDialogVisible = true
    },
    // 关闭对话框时重置表单信息
    rolesClosed() {
      this.$refs.rolesFormRef.resetFields()
    },
    //添加角色
    async addRole() {
      this.$refs.rolesFormRef.validate(async vaild => {
        if (!vaild) return
        const { data: res } = await this.$http.post('roles', {
          roleName: this.rolesRuleForm.roleName,
          roleDesc: this.rolesRuleForm.roleDesc
        })
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.addDialogVisible = false
        //自动刷新
        this.reload()
      })
    },
    //获取需要修改的角色信息
    async editRole(id) {
      const { data: res } = await this.$http.get(`roles/${id}`)
      this.editRolesRuleForm = res.data
      //只有获取完数据才可以将对话框的设置问true
      this.editRoleDialogVisible = true
    },
    //修改角色信息并提交验证
    aditRoleInfo() {
      this.$refs.editRolesFormRef.validate(async vaild => {
        if (!vaild) return
        const { data: res } = await this.$http.put(
          `roles/${this.editRolesRuleForm.roleId}`,
          {
            roleName: this.editRolesRuleForm.roleName,
            roleDesc: this.editRolesRuleForm.roleDesc
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.editRoleDialogVisible = false
        //自动刷新
        this.reload()
      })
    },
    //删除角色信息
    async deleteRole(id) {
      const { data: res } = await this.$http.delete(`roles/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      //自动刷新
      this.reload()
    },
    // 删除对应管理员的权限范围
    async removeRightById(rows, id) {
      // 点击确定返回confirm,点击取消返回cancel
     const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err);
        if(confirmResult !== 'confirm') {
          return this.$message.info("取消了本次操作")
        }
        const {data: res} = await this.$http.delete(`roles/${rows.id}/rights/${id}`);
        if(res.meta.status !== 200) {
          this.$message.error(res.meta.msg);
        }
        // 为防止页面刷新造成再次打开,直接将数据重新赋值给传来的数据
        rows.children = res.data;
    },
    //点击分配权限弹出对话框
   async setDialogRights(rows) {
     //将获取的id保存到数据以便分配权限
     this.RolesId = rows.id;
     //发起请求
     const {data: res} = await this.$http.get('rights/tree');
     if(res.meta.status !== 200) {
       return this.$message.error(res.meta.msg);
     }
     this.rightsList = res.data;
      // 使用递归获取角色列表中的id属性并存入数据
     this.getRightsRoles(rows, this.defKeysArr);
     //console.log(this.defKeysArr);
     this.setRightDialogVisible =true;
    },
    //递归获取角色权限下的id值
    //node为传入的对象,arr,保存的数组
    getRightsRoles(node, arr) {
      if(!node.children) {
        return arr.push(node.id);
      }
      //如果还存在就递归
      node.children.forEach(item => {
        this.getRightsRoles(item, arr);
      })
    },
    //监听获取的id重置,防止重复勾选的id
    resetDefKeysArr () {
      this.defKeysArr = []
    },
    //点击确定角色分配权限
    async setRightsRolesById() {
      // console.log(this.RolesId);
      //获取被选中的列表id,利用扩展运算符
      const RoleId = [
          ...this.$refs.treeRef.getCheckedKeys(),
      ]
      //将获取的数据拼接成字符串
      const isStr = RoleId.join(',');
      // console.log(isStr)
      //发起修改请求
      const {data: res} = await this.$http.post(`roles/${this.RolesId}/rights`,{
        rids: isStr
      });
      if(res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      this.$message.success(res.meta.msg);
      this.reload();
    }
  }
}
</script>
<style lang="less" scoped>
.el-tag {
  margin: 8px;
}
.bdTop {
  border-top: 1px solid #eee;
}
.bdBottom {
  border-bottom: 1px solid #eee;
}
.el-row {
  display: flex;
  align-items: center;
}
</style>
